﻿

using SimDev.ViewModel;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using WServer.ProtoBase;
using WServer.Service;

namespace SimDev
{ 


 

    public class DTUPackageInfo : IPackageInfo
    { 
        public byte[] Header { get; private set; }

        public byte[] Body { get; private set; }
     
        public string Key { get; private set; }
        public DTUPackageInfo(string key, byte[] body , byte[] header)            
        {
            Key = key;
             
            Header = header;
           
            Body = body;
        }
    
    
    }

    public class DTUReceiveFilter : FixedHeaderReceiveFilter<DTUPackageInfo>
    {
     
        public DTUReceiveFilter()
            : base(4)
        {

        }
       

        public override DTUPackageInfo ResolvePackage(IBufferStream bufferStream)
        {
            byte[] header = new Byte[HeaderSize];
            bufferStream.Read(header, 0, HeaderSize);
            //Debug.WriteLine(header.GetBytesString());
            int bodylen = (int)header[2] * 256 + (int)header[3];
       
            byte msgtype =  header[1];
            DTUPackageInfo requestinfo = null;

            byte[] body = new byte[bodylen];
            bufferStream.Read(body, 0, bodylen);

            if (MessageType.ContainsKey(msgtype))
            {
                var key = MessageType.GetKeyName(msgtype);

                requestinfo = new DTUPackageInfo(key, body, header);

                //if (msgtype == MessageType.DATA || msgtype == MessageType.DATA_HTTP)
                //    requestinfo = new DTUPackageInfo("DTUDATA", body, header);
                //else if (msgtype == MessageType.DTUHEARTBEAT)
                //    requestinfo = new DTUPackageInfo("DTUHEARTBEAT", body, header);


                return requestinfo;
            }
            else
            {
                return null;
            }
        }

        protected override int GetBodyLengthFromHeader(IBufferStream bufferStream, int length)
        {
            var header = new Byte[4];
            var oldpos = bufferStream.GetCurrentStream().Position;
            bufferStream.Read(header, 0, 4);
            //Debug.WriteLine(header.GetBytesString());
            int len = (int)header[2] * 256 + (int)header[3];
            if (len == 0)
                bufferStream.GetCurrentStream().Position = oldpos;
            return len;
        }

 

        
    }
    
}
